package com.xiaxueqi.web.demo;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.springframework.core.io.ClassPathResource;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import com.niagara.components.email.AsyncMailSender;
import com.niagara.rpc.annotation.RpcMethod;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class RpcDemo {
	private AsyncMailSender asyncMailSender;
	private Configuration freemarkerConfiguration;

	public void setAsyncMailSender(AsyncMailSender asyncMailSender) {
		this.asyncMailSender = asyncMailSender;
	}

	public void setFreemarkerConfiguration(Configuration freemarkerConfiguration) {
		this.freemarkerConfiguration = freemarkerConfiguration;
	}

	@RpcMethod
	public Map<String, String> testSendEmail() {
		Map<String, String> ret = new HashMap<String, String>();
		try {
			// 简单邮件测试
			this.asyncMailSender.sendMail("xiaxueqi.com@gmail.com",
					new String[] { "hejin016@gmail.com", "hejin016@126.com" },
					new String[] { "hejin016@sina.com" }, null, "邮件异步发送测试",
					"恭喜测试成功", null, null, null, false);
			// HTML加附件的邮件测试
			Map context = new HashMap();
			context.put("loginId", "testId");
			context.put("url", "http://www.xiaxueqi.com");

			Template template = freemarkerConfiguration.getTemplate(
					"regSuccess.ftl", AsyncMailSender.DEFAULT_ENCODING);
			String content = FreeMarkerTemplateUtils.processTemplateIntoString(
					template, context);// 使用FreeMarker渲染邮件内容
			ClassPathResource attachment = new ClassPathResource(
					"/email/doc.txt");// demo简单实用ClassPathResource
			// 附件内容也可以放到webapp下
			File f = attachment.getFile();
			// 测试发现图片作为附件比较容易被GMAIL当成垃圾邮件
			this.asyncMailSender.sendMail("xiaxueqi.com@gmail.com",
					new String[] { "hejin016@gmail.com", "hejin016@126.com" },
					new String[] { "hejin016@sina.com" }, null, "邮件异步发送测试",
					content, null, new File[] { f },
					new String[] { "wendang.txt" }, false);
			ret.put("ret", "OK");
		} catch (Exception e) {
			ret.put("ret", "SORRY");
		}

		return ret;
	}
}
